<template>
  <div class="prod2-container">
    <el-card class="search-card" shadow="never">
      <el-form :inline="true" :model="searchForm" label-width="90px" class="search-form">
        <el-form-item label="生产编号">
          <el-input v-model="searchForm.productionCode" placeholder="请输入生产编号" clearable style="width:220px" />
        </el-form-item>
        <el-form-item label="生产名称">
          <el-input v-model="searchForm.productionName" placeholder="请输入生产名称" clearable style="width:220px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="onSearch">查询</el-button>
          <el-button :icon="Refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <template #header>
        <div style="display:flex;justify-content:space-between;align-items:center;">
          <span style="font-weight:bold;">生产出入库</span>
          <div>
            <el-button type="primary" size="small" :icon="Plus" @click="onAdd">新增</el-button>
          </div>
        </div>
      </template>
      <el-table v-loading="loading" :data="tableData" size="small" border stripe style="width:100%">
        <el-table-column type="index" width="60" label="#" align="center" />
        <el-table-column prop="productionId" label="生产ID" align="center" min-width="100" show-overflow-tooltip />
        <el-table-column prop="productionCode" label="生产编号" align="center" min-width="140" show-overflow-tooltip />
        <el-table-column prop="productionName" label="生产名称" align="center" min-width="160" show-overflow-tooltip />
        <el-table-column prop="productionDept" label="部门" align="center" min-width="120" show-overflow-tooltip />
        <el-table-column prop="productionPerson" label="生产人" align="center" min-width="120" show-overflow-tooltip />
        <el-table-column prop="productionTime" label="生产时间" align="center" min-width="180" show-overflow-tooltip />
        <el-table-column prop="state" label="状态" align="center" min-width="100" show-overflow-tooltip />
        <el-table-column prop="productionNote" label="备注" show-overflow-tooltip min-width="220" />
        <!-- 按需求不显示 productCode -->
        <el-table-column label="操作" width="240" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" link @click="openProductDialog(scope.row)">产品管理</el-button>
            <el-button size="small" link @click="onEdit(scope.row)">编辑</el-button>
            <el-button size="small" link type="danger" @click="onDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10,20,50,100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>

    <!-- Add/Edit Dialog -->
    <el-dialog v-model="dialog.visible" :title="dialog.isEdit ? '编辑生产单' : '新增生产单'" width="640px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="formData" label-width="120px">
        <el-form-item label="生产编号">
          <el-input v-model="formData.productionCode" placeholder="请输入生产编号" />
        </el-form-item>
        <el-form-item label="生产名称">
          <el-input v-model="formData.productionName" placeholder="请输入生产名称" />
        </el-form-item>
        <el-form-item label="部门">
          <el-select v-model="formData.productionDept" placeholder="请选择部门" clearable filterable style="width:100%">
            <el-option v-for="d in deptOptions" :key="d.value" :label="d.label" :value="d.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="生产时间">
          <el-date-picker v-model="formData.productionTime" type="datetime" placeholder="选择时间" style="width:100%" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.productionNote" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="生产人">
          <el-select v-model="formData.productionPerson" placeholder="请选择入库人" clearable filterable style="width:100%">
            <el-option v-for="u in userOptions" :key="u.value" :label="u.label" :value="u.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formData.state" placeholder="请选择状态" style="width:100%">
            <el-option :value="0" label="未处理" />
            <el-option :value="1" label="已入库" />
            <el-option :value="2" label="已出库" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible=false">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 产品管理弹窗 -->
    <el-dialog v-model="productDialog.visible" title="产品管理" width="70%" align-center :close-on-click-modal="false">
      <div style="display:flex;align-items:center;margin-bottom:8px;gap:10px;">
        <el-button type="primary" size="small" @click="openProductSelect">新增</el-button>
        <div style="font-weight:600;">关联物料</div>
      </div>
      <el-table :data="productDialog.items" border size="small" style="width:100%">
        <el-table-column type="index" width="60" label="#" align="center" />
        <el-table-column prop="productCode" label="产品编号" width="160" show-overflow-tooltip />
        <el-table-column prop="productName" label="产品名称" width="160" show-overflow-tooltip />
        <el-table-column prop="spec" label="规格型号" width="180" show-overflow-tooltip />
        <el-table-column label="单位" width="80" align="center">
          <template #default="scope">{{ scope.row.unit || '件' }}</template>
        </el-table-column>
        <el-table-column label="接收数量" width="140" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.qty" size="small" placeholder="请输入" style="width: 110px" />
          </template>
        </el-table-column>
        <el-table-column label="批次号" width="180">
          <template #default="scope">
            <el-input v-model="scope.row.batchNo" size="small" placeholder="请输入批次号" />
          </template>
        </el-table-column>
        <el-table-column label="仓库" width="160">
          <template #default="scope">
            <el-select v-model="scope.row.warehouse" size="small" placeholder="选择仓库" style="width: 140px" @change="onWarehouseChange(scope.row)">
              <el-option v-for="w in productDialog.warehouses" :key="w.value" :label="w.label" :value="w.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="库区" width="140">
          <template #default="scope">
            <el-select v-model="scope.row.area" size="small" placeholder="选择库区" style="width: 120px" @change="onAreaChange(scope.row)">
              <el-option v-for="a in getAreaOptions(scope.row.warehouse)" :key="a.value" :label="a.label" :value="a.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="库位" width="140">
          <template #default="scope">
            <el-select v-model="scope.row.location" size="small" placeholder="选择库位" style="width: 120px">
              <el-option v-for="l in getLocationOptions(scope.row.warehouse, scope.row.area)" :key="l.value" :label="l.label" :value="l.value" />
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="productDialog.visible=false">返回</el-button>
          <el-button type="primary" @click="productDialog.visible=false">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 选择物料弹窗 -->
    <el-dialog v-model="productSelect.visible" title="选择物料" width="70%" align-center :close-on-click-modal="false">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
        <div>
          <el-button size="small" @click="selectAllProducts">全选本页</el-button>
          <el-button size="small" @click="invertSelectProducts">反选本页</el-button>
          <el-button size="small" @click="clearSelectProducts">清空选择</el-button>
        </div>
        <div>已选择 {{ productSelect.selectedIds.size }} 条</div>
      </div>
      <el-table ref="productSelectTableRef" :data="productSelect.list" border size="small" style="width:100%" :row-key="row => row.materialIds" @selection-change="onProductSelectionChange">
        <el-table-column type="selection" width="50" align="center" reserve-selection />
        <el-table-column type="index" label="#" width="60" align="center" />
        <el-table-column prop="materialCode" label="物料编码" width="150" show-overflow-tooltip />
        <el-table-column label="物料名称" width="160" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.mayrtName || scope.row.materialName || scope.row.mrialsName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="unitName" label="单位" width="100" align="center" />
        <el-table-column prop="specifications" label="规格型号" width="180" show-overflow-tooltip />
        <el-table-column prop="num" label="数量" width="100" align="center" />
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="productSelect.page"
          v-model:page-size="productSelect.size"
          :total="productSelect.total"
          :page-sizes="[10,20,50,100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="(s)=>{productSelect.size=s;loadProductList()}"
          @current-change="(p)=>{productSelect.page=p;loadProductList()}"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="productSelect.visible=false">取消</el-button>
          <el-button type="primary" @click="confirmSelectProducts">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/api/http'

const loading = ref(false)
const tableData = ref([])
const searchForm = reactive({ productionCode: '', productionName: '' })
const pagination = reactive({ page: 1, size: 10, total: 0 })

// dialog & form
const dialog = reactive({ visible: false, isEdit: false })
const formRef = ref(null)
const formData = reactive({
  productionId: 0,
  productionCode: '',
  productionName: '',
  productionDept: null,
  productionTime: '',
  productionNote: '',
  productionPerson: null,
  productCode: '',
  state: 0
})
const deptOptions = ref([])
const userOptions = ref([])

const loadData = async () => {
  loading.value = true
  try {
    const res = await http.get('api/WMS/GetProductionPage', {
      pageIndex: pagination.page,
      pageSize: pagination.size,
      productionCode: searchForm.productionCode || '',
      productionName: searchForm.productionName || ''
    })
    if (res && res.success) {
      tableData.value = Array.isArray(res.data) ? res.data : []
      pagination.total = res.total ?? tableData.value.length
    } else {
      ElMessage.error(res?.message || '获取数据失败')
    }
  } catch (e) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const onSearch = () => { pagination.page = 1; loadData() }
const onReset = () => { searchForm.productionCode = ''; searchForm.productionName=''; pagination.page=1; loadData() }
const onSizeChange = (s) => { pagination.size = s; pagination.page = 1; loadData() }
const onPageChange = (p) => { pagination.page = p; loadData() }

onMounted(async () => {
  loadData()
  try {
    const [deptRes, userRes] = await Promise.all([
      http.get('api/WMS/GetAllDepts'),
      http.get('api/WMS/GetAllUsers')
    ])
    if (deptRes && deptRes.success) {
      deptOptions.value = (deptRes.data || []).map(x => ({ value: x.id || x.deptId || x.departmentId, label: x.departmentName || x.deptName || x.name }))
    }
    if (userRes && userRes.success) {
      userOptions.value = (userRes.data || []).map(x => ({ value: x.userId || x.id, label: x.userTrueName || x.userName || x.name }))
    }
  } catch (e) { /* ignore */ }
})

// CRUD
const onAdd = () => {
  dialog.isEdit = false
  dialog.visible = true
  Object.assign(formData, { productionId: 0, productionCode: '', productionName: '', productionDept: null, productionTime: '', productionNote: '', productionPerson: null, productCode: '', state: 0 })
}

const onEdit = async (row) => {
  dialog.isEdit = true
  dialog.visible = true
  try {
    const res = await http.get('api/WMS/GetProductionById', { id: row.productionId })
    if (res && res.success && res.data) {
      Object.assign(formData, {
        productionId: res.data.productionId,
        productionCode: res.data.productionCode,
        productionName: res.data.productionName,
        productionDept: res.data.productionDept ?? null,
        productionTime: res.data.productionTime ? new Date(res.data.productionTime).toISOString() : '',
        productionNote: res.data.productionNote || '',
        productionPerson: res.data.productionPerson ?? null,
        productCode: res.data.productCode || '',
        state: res.data.state ?? 0
      })
    } else {
      ElMessage.error(res?.message || '获取详情失败')
    }
  } catch (e) {
    ElMessage.error('获取详情失败')
  }
}

const onSubmit = async () => {
  const payload = {
    productionId: dialog.isEdit ? formData.productionId : 0,
    productionCode: formData.productionCode,
    productionName: formData.productionName,
    productionDept: formData.productionDept ?? 0,
    productionTime: formData.productionTime ? new Date(formData.productionTime).toISOString() : '',
    productionNote: formData.productionNote,
    productionPerson: formData.productionPerson ?? 0,
    productCode: formData.productCode || '',
    state: formData.state ?? 0
  }
  try {
    const res = dialog.isEdit
      ? await http.put('api/WMS/ProductionUpdate', payload, '提交中...')
      : await http.post('api/WMS/ProductionAdd', payload, '提交中...')
    if (res && (res.success || res.status)) {
      ElMessage.success('保存成功')
      dialog.visible = false
      loadData()
    } else {
      ElMessage.error(res?.message || '保存失败')
    }
  } catch (e) {
    ElMessage.error('保存失败')
  }
}

const onDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该记录吗？', '提示', { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' })
  } catch {
    return
  }
  const payload = {
    productionId: row.productionId,
    productionCode: row.productionCode,
    productionName: row.productionName,
    productionDept: row.productionDept,
    productionTime: row.productionTime ? new Date(row.productionTime).toISOString() : '',
    productionNote: row.productionNote,
    productionPerson: row.productionPerson,
    productCode: row.productCode || '',
    state: row.state ?? 0
  }
  try {
    const res = await http.del('api/WMS/ProductionDelete', payload, '删除中...')
    if (res && (res.success || res.status)) {
      ElMessage.success('删除成功')
      loadData()
    } else {
      ElMessage.error(res?.message || '删除失败')
    }
  } catch (e) {
    ElMessage.error('删除失败')
  }
}

// 产品管理：状态与方法（与物料页面一致）
const productDialog = reactive({
  visible: false,
  items: [],
  headerId: null,
  warehouses: [],
  areasRaw: [],
  locationsRaw: []
})
const productSelect = reactive({ visible: false, page: 1, size: 10, total: 0, list: [], selectedIds: new Set() })
const productSelectTableRef = ref(null)

const openProductDialog = async (row) => {
  productDialog.headerId = row.productionId
  // 加载仓库/库区/库位
  try {
    const [wRes, aRes, lRes] = await Promise.all([
      http.get('api/WarehouseQuery/GetAllWarehouseModelling'),
      http.get('api/WarehouseQuery/GetAllReservoirareaModelling'),
      http.get('api/WarehouseQuery/GetAllStorageLocationModelling')
    ])
    if (wRes && wRes.success) productDialog.warehouses = (wRes.data || []).map(x => ({ value: x.id, label: x.warehouseName }))
    if (aRes && aRes.success) productDialog.areasRaw = aRes.data || []
    if (lRes && lRes.success) productDialog.locationsRaw = lRes.data || []
  } catch (e) { /* ignore */ }
  productDialog.items = []
  productDialog.visible = true
}

const openProductSelect = () => {
  productSelect.visible = true
  productSelect.page = 1
  loadProductList(true)
}
const loadProductList = async (resetSelection=false) => {
  // 使用与退料出入库相同的数据源：物料分页
  const res = await http.get('api/WMS/GetMaterialsFromApiPage', { pageIndex: productSelect.page, pageSize: productSelect.size })
  if (res && res.success) {
    productSelect.list = res.data || []
    productSelect.total = res.total || 0
    if (resetSelection && productSelectTableRef.value) {
      productSelectTableRef.value.clearSelection()
      productSelect.selectedIds.clear()
    }
  }
}
const selectAllProducts = () => {
  if (!productSelectTableRef.value) return
  productSelect.list.forEach(row => {
    productSelectTableRef.value.toggleRowSelection(row, true)
    productSelect.selectedIds.add(row.materialIds)
  })
}
const invertSelectProducts = () => {
  if (!productSelectTableRef.value) return
  productSelect.list.forEach(row => {
    const selected = productSelect.selectedIds.has(row.materialIds)
    productSelectTableRef.value.toggleRowSelection(row, !selected)
    if (selected) productSelect.selectedIds.delete(row.materialIds); else productSelect.selectedIds.add(row.materialIds)
  })
}
const clearSelectProducts = () => {
  if (!productSelectTableRef.value) return
  productSelectTableRef.value.clearSelection()
  productSelect.selectedIds.clear()
}
const onProductSelectionChange = (rows) => {
  const ids = new Set(rows.map(r => r.materialIds))
  productSelect.selectedIds = ids
}
const confirmSelectProducts = () => {
  const selectedRows = productSelect.list.filter(x => productSelect.selectedIds.has(x.materialIds))
  selectedRows.forEach(x => {
    productDialog.items.push({
      id: x.materialIds,
      productCode: x.materialCode,
      productName: x.mayrtName || x.materialName || x.mrialsName || '',
      spec: x.specifications || '',
      unit: x.unitName || '',
      qty: '',
      batchNo: '',
      warehouse: null,
      area: null,
      location: null
    })
  })
  productSelect.visible = false
}

// 联动
const onWarehouseChange = (row) => { row.area = null; row.location = null }
const onAreaChange = (row) => { row.location = null }
const getAreaOptions = (warehouseId) => {
  if (!warehouseId) return []
  return (productDialog.areasRaw || []).filter(a => a.cId === warehouseId).map(a => ({ value: a.id, label: a.reservoirareaName }))
}
const getLocationOptions = (warehouseId, areaId) => {
  if (!warehouseId) return []
  return (productDialog.locationsRaw || []).filter(l => l.cId === warehouseId).map(l => ({ value: l.id, label: l.storagelocationName }))
}
</script>

<style lang="less" scoped>
.prod2-container { padding: 20px; }
.search-card { margin-bottom: 16px; }
.pagination-container { margin-top: 16px; display: flex; justify-content: flex-end; }
::deep(.el-table__row) { height: 36px; }
::deep(.el-table .cell) { line-height: 36px; padding: 6px 10px; }
</style>



